package com.jsgt.greekfire.ui.trading.otc

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.common.util.CountDownTimerUtils
import com.jsgt.greekfire.common.util.MD5Util
import com.jsgt.greekfire.event.ExitEvent
import com.jsgt.greekfire.factory.OTCTraddingModelFactory
import com.jsgt.greekfire.viewmodel.OTCTraddingViewModel
import kotlinx.android.synthetic.main.activity_buy_otc.*
import kotlinx.android.synthetic.main.activity_buy_otc.btnBuy
import kotlinx.android.synthetic.main.activity_buy_otc.etAmount
import kotlinx.android.synthetic.main.activity_buy_otc.etNum
import kotlinx.android.synthetic.main.activity_buy_otc.etPwd
import kotlinx.android.synthetic.main.activity_buy_otc.tvAmount
import kotlinx.android.synthetic.main.activity_buy_otc.tvCoinCode
import kotlinx.android.synthetic.main.activity_buy_otc.tvSec
import kotlinx.android.synthetic.main.activity_buy_otc.tvWholeNum
import kotlinx.android.synthetic.main.activity_buy_otc.tvusdt
import kotlinx.android.synthetic.main.activity_sell_otc.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.backgroundColor

class BuyOTCActivity : BaseActivity() {
    var tvTitle: TextView? = null
    var title_layout: RelativeLayout? = null
    private var flag = false
    var bundle: Bundle? = null
    var dealNum: String? = null
    var usdt: String? = null
    var dealAmount: String? = null
    var guid: String? = null
    var title: String? = null
    var coinCode: String? = null
    var back: ImageView? = null
    private val DECIMAL_DIGITS = 4 //小数的位数
    private var mCountDownTimerUtils:CountDownTimerUtils ? = null

    override fun getLayoutId(): Int = R.layout.activity_buy_otc
    private val otcTraddingViewModel: OTCTraddingViewModel by lazy {
        ViewModelProvider(
            this,
            OTCTraddingModelFactory()
        ).get(OTCTraddingViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bundle = intent.extras
        dealNum = bundle?.getString("dealNum")
        usdt = bundle?.getString("usdt")
        dealAmount = bundle?.getString("dealAmount")
        guid = bundle?.getString("guid")
        setStatusBar(R.color.buy_order_2C2D3A, false, R.color.white)

    }

    override fun onStart() {
        super.onStart()
        if (!TextUtils.isEmpty(dealAmount)) {
            var num = dealAmount!!.toFloat() * 7
            tvusdt?.text = "¥$num"
        }
    }

    override fun main() {

        bundle = intent.extras
        coinCode = bundle?.getString("coinCode")
        initView()

        tvWholeNum.setOnClickListener { v ->
            etNum?.setText(dealNum)
        }
        tvAmount.setOnClickListener { v ->
            etAmount?.setText(usdt)
        }


        btnBuy.setOnClickListener { v ->
            if (verifyInfo(
                    etNum?.text.toString().trim(),
                    etAmount?.text.toString().trim(),
                    etPwd?.text.toString().trim()
                )
            ) {
                //ToastUtils.show("购买")
                showProgress(true)
                otcTraddingViewModel.getAddOrder(
                    etNum?.text.toString().trim(),
                    guid!!,
                    MD5Util.getMD5(etPwd?.text.toString().trim())
                )
            }
        }

        otcTraddingViewModel.AddOrderData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show("已提交")
            finish()
        })
        otcTraddingViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(it.toString())

        })

    }


    private fun initView() {
        bundle = intent.extras
        title = bundle?.getString("title")
        tvCoinCode.setText(title!!)
        tvTitle = findViewById(R.id.title_tv)
        back = findViewById(R.id.back)
        title_layout = findViewById(R.id.title_layout)
        tvTitle?.text = "购买" + title
        title_layout?.backgroundColor = resources.getColor(R.color.buy_order_2C2D3A)

//        etNum.setFilters(arrayOf<InputFilter>(DecimalDigitsInputFilter(4)))
//        etAmount.setFilters(arrayOf<InputFilter>(DecimalDigitsInputFilter(4)))


        mCountDownTimerUtils = CountDownTimerUtils(tvSec!!, 60000, 1000, 0)
        mCountDownTimerUtils?.start()

        etNum.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (s.toString().contains(".")) {
                    if (s.length - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        var s = s.toString().subSequence(
                            0,
                            s.toString().indexOf(".") + DECIMAL_DIGITS + 1
                        );
                        etNum.setText(s);
                        etNum.setSelection(s.length);
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    var s = "0" + s;
                    etNum.setText(s);
                    etNum.setSelection(2);
                }
                if (s.toString().startsWith("0")
                    && s.toString().trim().length > 1
                ) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etNum.setText(s.subSequence(0, 1));
                        etNum.setSelection(1);
                        return;
                    }
                }

            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int,
                after: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                if (flag) {
                    return;
                }
                flag = true;

                //功能实现部分
              /*  btnBuy?.isEnabled =
                    etNum.text.toString().trim().isNotEmpty() && etAmount.text.toString()
                        .trim().isNotEmpty() && etPwd.text.toString().trim().isNotEmpty()*/
                if (s.toString().trim().contains(".") || s.toString().trim().startsWith("0")) {
                    if (s.toString().trim().length <= 2){
                        etAmount?.setText("")
                        flag = false;
                        return
                    }
                }
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    var num = s.toString().trim().toFloat()
                    var p = dealAmount!!.toFloat()
                    var n = num * p
                    etAmount?.setText(n.toString())
                } else {
                    etAmount?.setText("")
                }
                flag = false;
            }
        })

        etAmount.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(
                s: CharSequence, start: Int, before: Int,
                count: Int
            ) {
                if (s.toString().contains(".")) {
                    if (s.length - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        var s = s.toString().subSequence(
                            0,
                            s.toString().indexOf(".") + DECIMAL_DIGITS + 1
                        );
                        etAmount.setText(s);
                        etAmount.setSelection(s.length);
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    var s = "0" + s;
                    etAmount.setText(s);
                    etAmount.setSelection(2);
                }
                if (s.toString().startsWith("0")
                    && s.toString().trim().length > 1
                ) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etAmount.setText(s.subSequence(0, 1));
                        etAmount.setSelection(1);
                        return;
                    }
                }
            }

            override fun beforeTextChanged(
                s: CharSequence, start: Int, count: Int,
                after: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                if (flag) {
                    return;
                }
                flag = true;
              /*  btnBuy?.isEnabled =
                    etNum.text.toString().trim().isNotEmpty() && etAmount.text.toString()
                        .trim().isNotEmpty() && etPwd.text.toString().trim().isNotEmpty()*/
                if (s.toString().trim().contains(".") || s.toString().trim().startsWith("0")) {
                    if (s.toString().trim().length <= 2){
                        etNum?.setText("")
                        flag = false;
                        return
                    }
                }
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    var num = s.toString().trim().toFloat()
                    var p = dealAmount!!.toFloat()
                    var n = num / p
                    etNum?.setText(n.toString())
                } else {
                    etNum?.setText("")
                }
                flag = false;
            }
        })
        back?.setOnClickListener { v ->
            finish()
            otcTraddingViewModel.getotcAdStateData(guid!!, "0")
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onExit(e: ExitEvent) {
        otcTraddingViewModel.getotcAdStateData(guid!!, "0")
        //购买倒计时结束 退出界面
        finish()
    }


    override fun onPause() {
        otcTraddingViewModel.getotcAdStateData(guid!!, "0")
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mCountDownTimerUtils?.cancel()
    }

    private fun verifyInfo(
        num: String,
        amount: String,
        pwd: String
    ): Boolean {
        if (TextUtils.isEmpty(num)) {
            showToast(resources.getString(R.string.buy_coin_text1))
            return false
        } else if (TextUtils.isEmpty(amount)) {
            showToast(resources.getString(R.string.buy_coin_text3))
            return false
        } else if (TextUtils.isEmpty(pwd)) {
            showToast(resources.getString(R.string.sell_gfc_text7))
            return false
        }
        return true
    }
}